package com.acme.bankapp.service.bank;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.acme.bankapp.domain.bank.Account;
import com.acme.bankapp.domain.bank.Bank;
import com.acme.bankapp.domain.bank.CheckingAccount;
import com.acme.bankapp.domain.bank.Client;

public class BankReport {
	
	public static int getNbOfCustomers(Bank bank) {
		return bank.getClients().size();
	}
	
	public static int getNbOfAccounts(Bank bank) {
		int count = 0;
		for (Client client: bank.getClients()) {
			count += client.getAccounts().size();
		}
		return count;
	}
	
	public static class AccountComparator implements Comparator<Account> {
	    public int compare(Account first, Account second) {
	    	double firstValue = first.maximumAmountToWithdraw();
	    	double secondValue = second.maximumAmountToWithdraw();
	    	if (firstValue < secondValue) {
	    		return -1;
	    	} else if (firstValue == secondValue) {
	    		return 0;
	    	} else {
	    		return 1;
	    	}
	    }
	}
	
	public static List<Account> getAccountsSortedBySum(Bank bank) {
        int count = getNbOfAccounts(bank);
        Comparator<Account> comparator = new AccountComparator();
		List<Account> result = new ArrayList<Account>(count);
        for (Client client : bank.getClients()) {
            for (Account account : client.getAccounts()) {
                result.add(account);
            }
        }
        Collections.sort(result, comparator);
        return result;	
	}


	public static double getBankCredit(Bank bank) {
		double count = 0;
		for (Client client: bank.getClients()) {
			for (Account account: client.getAccounts()) {
				if (account instanceof CheckingAccount) {
					CheckingAccount checkingAccount = (CheckingAccount)account;
					count += checkingAccount.getCredit();
				}
			}
		}	
		return count;
	}

    static Map<Client, Set<Account>> getCustomerAccount(Bank bank) {
        Map<Client, Set<Account>> result = new HashMap<Client, Set<Account>>();        
        for (Client client : bank.getClients()) {
            result.put(client, client.getAccounts());
        }        
        return result;
    }
}
